﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using VisionRoc.Core;

namespace VisionRoc_Measure
{
    public partial class FormFindData : Form
    {
        public FormFindData()
        {
            InitializeComponent();
        }
        DataTable dt;

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormFindData_Load(object sender, EventArgs e)
        {
            try
            {
                dataGridView1.RowsDefaultCellStyle.BackColor = Color.White;
                dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.WhiteSmoke;
                dataGridView1.TopLeftHeaderCell.Value = "序号";
                dataGridView1.RowHeadersWidth = 80;
                //最后一行不显示
                dataGridView1.AllowUserToAddRows = false;

                string result = "";
                Global.m_MultiLanguage.LControls = new List<Control>();
                Global.m_MultiLanguage.GetControls(this);
                if (!Global.m_MultiLanguage.LoadLanguage(this, out result))
                {
                    MessageBox.Show(result + "\r\n程序当前语言可能异常，如果影响正常使用请重新启动程序", "加载语言", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
         
        }

        string m_Path;

        /// <summary>
        /// 打开RocCsv文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Run_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog Save = new FolderBrowserDialog();
            Save.Description = "请选择文件夹路径";
            Save.ShowDialog();
            if (Save.SelectedPath != "")
            {
                string fileName = Path.GetFileName(Save.SelectedPath);
                if(fileName=="RocCsv")
                {
                    m_Path = Save.SelectedPath;
                    this.treeView1.Nodes.Clear();
                    FileTreeView fileTreeView = new FileTreeView(treeView1, m_Path);
                    fileTreeView.PopulateTreeView();
                    this.treeView1.ExpandAll();
                }
                else
                {
                    MessageBox.Show("请选择本系统RocCsv文件");
                }
               
            }
        }

        /// <summary>
        /// 双击树节点打开csv
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {

            if (Directory.Exists(m_Path)) // 判断当前路径是否存在
            {
                string str1 = m_Path + "\\" + GetTreeViewPath(treeView1);
                if (IsCsvFile(str1))//判断文件是否为CSV文件
                {
                    if (File.Exists(str1))//判断文件是否存在
                    {
                        if(dataGridView1.Rows.Count>0)
                        {
                            dataGridView1.DataSource = null;
                        }
                       
                        dt = readCSV(str1);
                        dataGridView1.DataSource = dt;
                        //DispDataMessage(str1);
                    }
                    else
                    {
                        MessageBox.Show("当前Csv文件不存在");
                    }
                }
                else
                {
                    //不是CSV文件
                }
            }
            else
            {
                //路径不存在
            }
        }

        /// <summary>
        /// 查询信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_FindData_Click(object sender, EventArgs e)
        {
            FindData(txt_FindData.Text, dataGridView1, comboBox1);
        }

        #region MyRegion

       
        /// <summary>
        /// 打开csv文件复制到datagridview
        /// </summary>
        private void OpenFile(DataGridView dataGridView, ComboBox comboBox)
        {
            try
            {
                string path;
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.InitialDirectory = Application.StartupPath + "\\SaveData";
                ofd.RestoreDirectory = true;
                ofd.Filter = "CSV UTF-8(逗号分隔)(.csv)|*.csv|CSV(逗号分隔)(.csv)|*.csv";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    path = ofd.FileName;
                    //txb_SavePath.Text = path;
                    string ext = Path.GetExtension(path);

                    dt = new DataTable();
                    System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open);
                    System.IO.StreamReader sr = new System.IO.StreamReader(fs, Encoding.GetEncoding("gb2312"));

                    string tempText = "";
                    bool isFirst = true;
                    this.Invoke(new MethodInvoker(() =>
                    {
                        while ((tempText = sr.ReadLine()) != null)
                        {
                            string[] arr = tempText.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                            if (isFirst)
                            {
                                foreach (string str in arr)
                                {
                                    dt.Columns.Add(str);
                                }
                                isFirst = false;
                            }
                            else
                            {
                                DataRow dr = dt.NewRow();
                                for (int i = 0; i < dt.Columns.Count; i++)
                                {
                                    dr[i] = i < arr.Length ? arr[i] : "";
                                }
                                dt.Rows.Add(dr);
                            }
                        }
                        dataGridView.DataSource = dt;
                    }));

                    foreach (DataColumn column in dt.Columns)
                    {
                        comboBox.Items.Add(column.ColumnName);
                    }
                    comboBox.SelectedIndex = 0;
                    sr.Close();
                    fs.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载文件异常失败..." + ex.ToString());
            }
        }

        /// <summary>
        /// 查找数据复制到控件上
        /// </summary>
        /// <param name="data"></param>
        private void FindData(string data, DataGridView dataGridView, ComboBox comboBox)
        {
            try
            {
                if (dt == null) return;
                string str = data.Trim();
                if (string.IsNullOrEmpty(str))
                {
                    dt.DefaultView.RowFilter = "";
                }
                Query(dt, dataGridView, comboBox.Text, str);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        /// <summary>
        /// 查找数据源
        /// </summary>
        /// <param name="dtSource"></param>
        /// <param name="colun"></param>
        /// <param name="filter"></param>
        private void Query(DataTable dtSource, DataGridView dataGridView, string colun, string filter)
        {
            string strTemp = $"{colun} like '%" + filter + "%'";//
            DataRow[] drArr1 = dtSource.Select(strTemp);
            DataTable dtNew = dtSource.Clone();
            for (int i = 0; i < drArr1.Length; i++)
            {
                dtNew.ImportRow(drArr1[i]); //ImportRow 是复制

            }
            //重新绑定数据源
            dataGridView.DataSource = null;
            dataGridView.DataSource = dtNew;
        }

        /// <summary>
        /// 获取选中的节点的所有父节点 组成路径返回
        /// </summary>
        /// <param name="treeView"></param>
        /// <returns></returns>
        private string GetTreeViewPath(TreeView treeView)
        {
            List<String> NameList = new List<string>();
            GetParentsName(treeView.SelectedNode, ref NameList);
            NameList.Reverse();
            string path = "";
            for (int i = 0; i < NameList.Count; i++)
            {
                if (i != 0)
                {
                    if (i == NameList.Count - 1)
                    {
                        path += NameList[i];
                    }
                    else
                    {
                        path += NameList[i] + "\\";
                    }
                }

            }
            return path;
        }

        /// <summary>
        /// 获取TreeView 父节点
        /// </summary>
        /// <param name="Node"></param>
        /// <param name="NameList"></param>
        private void GetParentsName(TreeNode Node, ref List<String> NameList)
        {
            try
            {
                NameList.Add(Node.Text);
                if (Node.Parent != null)
                {
                    //递归
                    GetParentsName(Node.Parent, ref NameList);
                }
            }
            catch
            {

            }
          
        }

        /// <summary>
        /// 判断是否是CSV文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public bool IsCsvFile(string filePath)
        {
            string extension = Path.GetExtension(filePath);
            return extension != null && extension.Equals(".csv", StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// 将路径下的CSV文件读取到dt
        /// </summary>
        /// <param name="path1"></param>
        private void DispDataMessage(string path1)
        {
            try
            {
                //dataGridView1.Rows.Clear();
                dt = new DataTable();
                System.IO.FileStream fs = new System.IO.FileStream(path1, System.IO.FileMode.Open);
                System.IO.StreamReader sr = new System.IO.StreamReader(fs, Encoding.GetEncoding("gb2312"));

                string tempText = "";
                bool isFirst = true;
                this.Invoke(new MethodInvoker(() =>
                {
                    while ((tempText = sr.ReadLine()) != null)
                    {
                        string[] arr = tempText.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        if (isFirst)
                        {
                            foreach (string str in arr)
                            {
                                dt.Columns.Add(str);
                            }
                            isFirst = false;
                        }
                        else
                        {
                            DataRow dr = dt.NewRow();
                            for (int i = 0; i < dt.Columns.Count; i++)
                            {
                                dr[i] = i < arr.Length ? arr[i] : "";
                            }
                            dt.Rows.Add(dr);
                        }
                    }
                    dataGridView1.DataSource = dt;
                }));
                comboBox1.Items.Clear();
                foreach (DataColumn column in dt.Columns)
                {
                    comboBox1.Items.Add(column.ColumnName);
                }
                comboBox1.SelectedIndex = 0;
                sr.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        /// <summary>
        /// 将CSV文件的数据读取到DataTable中
        /// </summary>
        /// <param name="fileName">CSV文件路径</param>
        /// <returns>返回读取了CSV数据的DataTable</returns>
        public System.Data.DataTable readCSV(string fileName)
        {

            DataTable dt = new DataTable();
            try
            {
                FileStream fs = new FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);


                //记录每次读取的一行记录
                string strLine = "";
                //记录每行记录中的各字段内容
                string[] aryLine;
                //标示列数
                int columnCount = 0;
                //标示是否是读取的第一行
                bool IsFirst = true;

                //逐行读取CSV中的数据
                while ((strLine = sr.ReadLine()) != null)
                {
                    aryLine = strLine.Split(',');
                    if (IsFirst == true)
                    {
                        IsFirst = false;
                        columnCount = aryLine.Length;
                        //创建列
                        for (int i = 0; i < columnCount; i++)
                        {

                            DataColumn dc = new DataColumn(aryLine[i]);
                            dt.Columns.Add(dc);

                        }
                    }
                    else
                    {
                        int nullCount = 0;
                        DataRow dr = dt.NewRow();
                        for (int j = 0; j < columnCount; j++)
                        {
                            if (aryLine[j] != "")
                            {
                                dr[j] = aryLine[j];

                            }
                            else
                            {
                                dr[j] = "null";
                                nullCount += 1;
                            }
                        }
                        if (nullCount >= 6)
                        {

                        }
                        else
                        {
                            dt.Rows.Add(dr);
                        }

                    }
                }
                comboBox1.Items.Clear();
                foreach (DataColumn column in dt.Columns)
                {
                    comboBox1.Items.Add(column.ColumnName);
                }
                comboBox1.SelectedIndex = 0;
                sr.Close();
                fs.Close();
                return dt;
            }
            catch
            {

                return dt = null;
            }
        }

        #endregion

        private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            //增加行号的显示格式
            e.Row.HeaderCell.Value = e.Row.Index.ToString().PadLeft(1, '1');
        }
    }

}




public class FileTreeView
{
    private TreeView treeView;
    private string rootPath;

    public FileTreeView(TreeView treeView, string rootPath)
    {
        this.treeView = treeView;
        this.rootPath = rootPath;
    }

    public void PopulateTreeView()
    {
        treeView.Nodes.Clear();
        TreeNode rootNode = treeView.Nodes.Add(Path.GetFileName(rootPath), Path.GetFileName(rootPath));
        AddDirectories(rootNode, new DirectoryInfo(rootPath));
        treeView.ExpandAll();
    }

    private void AddDirectories(TreeNode node, DirectoryInfo directory)
    {
        foreach (DirectoryInfo subDir in directory.GetDirectories())
        {
            TreeNode subNode = node.Nodes.Add(subDir.Name);
            AddDirectories(subNode, subDir);
        }
        foreach (FileInfo file in directory.GetFiles())
        {
            node.Nodes.Add(file.Name);
        }
    }

}

